package com.example.springboottestgit.controller.main;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.vo.InputVO;
import com.example.springboottestgit.bean.vo.TextVO;
import com.example.springboottestgit.utils.ExcelExportUtil;
import com.example.springboottestgit.utils.HttpUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: ZZZ
 */
public class Qwen2API {
    static int question_count = 0;
    static int file_count = 0;

    static List<TextVO> list = new ArrayList<>();


    public static void main(String[] args) throws IOException {
        String path = "C:\\Users\\ZZZ\\Desktop\\莆田市财政局(1)\\2005-2017";
        //searchFile(new File(path));

        //System.out.println(JSONObject.toJSONString(list));
        //System.out.println("=========excel==========");
        String outputFilePath = "C:\\Users\\user\\Desktop\\莆田市财政局\\test.xlsx";
        //export(list, outputFilePath);
        //System.out.println("文件总数：" + file_count);
        //System.out.println("问题总数：" + question_count);
        //FileUtil.txtWriter(path + "\\test.txt", JSONObject.toJSONString(list));

        //从文件获取List数据（源数据），然后再保持到excel
        lastList();


    }

    public static void lastList() throws IOException {
        List<TextVO> result = new ArrayList<>();
//        list.addAll(getList("C:\\Users\\user\\Desktop\\莆田市财政局(1)\\1.txt"));
//        list.addAll(getList("C:\\Users\\user\\Desktop\\莆田市财政局(1)\\2.txt"));
//        list.addAll(getList("C:\\Users\\user\\Desktop\\莆田市财政局(1)\\3.txt"));
//        list.addAll(getList("C:\\Users\\user\\Desktop\\莆田市财政局(1)\\4.txt"));
        list.addAll(getList("C:\\Users\\user\\Desktop\\莆田市财政局(1)\\last.txt"));
        System.out.println(list.size());
        int m = 0;
        for (TextVO vo : list) {
            if (vo.getContent().length() < 50) {
                //m++;
//                String question = "请帮我围绕以下标题和内容生成三个相关的问题，必须用中文回答，问题和内容如下：\n";
//                String fileNameText = "标题：" + vo.getFileName().substring(0, vo.getFileName().indexOf(".")) + "\n";
//                InputVO inputVO = new InputVO();
//                String text=getTextContent(vo.getFilePath());
//                if(text.length()>6000){
//
//                }
//                String newText=text.length()>6000?text.substring(0,6000):text;
//                inputVO.setQuestion(question + fileNameText + "内容：\n" + newText);
//                String param = JSONObject.toJSONString(inputVO);
//
//                String result = HttpUtils.post("http://192.168.80.35:8092/qwen2/7B/api", param);
//                result = result.replace("?", "？");
//                vo.setContent(result);
            }

            String content = vo.getContent();
            String[] split = content.split("？");
            if (split.length >= 3) {
                for (int i = 0; i < 2; i++) {
                    String question = split[i];
                    int k = 0;
                    if (question.contains("1.")) {
                        k = question.indexOf("1.") + 2;
                    } else if (question.contains("2.")) {
                        k = question.indexOf("2.") + 2;
                    } else if (question.contains("3.")) {
                        k = question.indexOf("3.") + 2;
                    }

                    TextVO newVo = new TextVO();
                    newVo.setFileName(vo.getFileName());
                    newVo.setFilePath(vo.getFilePath());
                    newVo.setContent(vo.getContent());
                    newVo.setQuestion(question.substring(k).trim()+"？");
                    result.add(newVo);

                }

            }
        }
        System.out.println(m);
        String outputFilePath = "C:\\Users\\user\\Desktop\\莆田市财政局(1)\\test.xlsx";
        export(result, outputFilePath);

        //FileUtil.txtWriter( "C:\\Users\\user\\Desktop\\莆田市财政局(1)\\last.txt", JSONObject.toJSONString(list));
    }

    public static List<TextVO> getList(String path) throws IOException {
        String s = getTextContent(path);
        List<TextVO> list = JSON.parseArray(s, TextVO.class);

        return list;

    }

    public static void searchFile(File dir) throws IOException {
        boolean found = false;//如果没找到要给出回应
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();//用数组遍历文件夹中的文件
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isFile()) {
                        if (file.getName().equals("test.txt")) {
                            continue;
                        }
                        String text = getTextContent(file.getPath());
                        qwenapi(file.getName(), file.getPath(), text);
                    } else {
                        searchFile(file);//递归运算
                    }
                }
            }
        } else {
            System.out.println("当前搜索的位置不是文件夹！");
        }
    }

    public static void qwenapi(String fileName, String filePath, String text) throws IOException {
        file_count++;
        System.out.println("文件总数：" + file_count);

        LocalDateTime s = LocalDateTime.now();

        System.out.println(fileName);
        System.out.println(text.length());
        String question = "请帮我围绕以下标题和内容生成三个相关的问题，必须用中文回答，问题和内容如下：\n";
        String fileNameText = "标题：" + fileName.substring(0, fileName.indexOf(".")) + "\n";
        InputVO inputVO = new InputVO();
        inputVO.setQuestion(question + fileNameText + "内容：\n" + text);
        String param = JSONObject.toJSONString(inputVO);

        String result = HttpUtils.post("http://192.168.80.35:8092/qwen2/7B/api", param);
        result = result.replace("?", "？");
        System.out.println(result);
        TextVO vo = new TextVO();
        vo.setFileName(fileName);
        vo.setFilePath(filePath);
        vo.setContent(result);
        list.add(vo);

        /**
         String[] split = result.split("？");
         if (split.length == 0) {
         TextVO vo = new TextVO();
         vo.setFileName(fileName);
         vo.setFilePath(filePath);
         list.add(vo);
         }
         int n = 0;
         for (String s1 : split) {
         n++;
         int index = s1.indexOf(". ");
         if (index == -1) {
         TextVO vo = new TextVO();
         vo.setFileName(fileName);
         vo.setFilePath(filePath);
         list.add(vo);
         question_count++;
         break;
         }
         String q = s1.substring(index + 1).replace(" ", "") + "？";

         System.out.println("问题：" + q);
         if (n == 1) {
         TextVO vo = new TextVO();
         vo.setFileName(fileName);
         vo.setFilePath(filePath);
         vo.setQuestion(q);
         list.add(vo);
         question_count++;
         } else if (n == 2) {
         TextVO vo = new TextVO();
         vo.setFileName(fileName);
         vo.setFilePath(filePath);
         vo.setQuestion(q);
         list.add(vo);
         question_count++;
         } else {
         break;
         }
         }
         **/
        LocalDateTime e = LocalDateTime.now();

        Duration between = Duration.between(s, e);
        System.out.println("耗时：" + between.getSeconds());
        System.out.println();
    }

    public static String getTextContent(String path) throws IOException {
        List<KY> list = new ArrayList<>();
        FileReader reader = new FileReader(path);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }

    public static String getTextContent2(String path) throws IOException {
        List<KY> list = new ArrayList<>();
        FileReader reader = new FileReader(path);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }

    public static void export(List<TextVO> result, String outputFilePath) {

        List<Map<String, Object>> list = JSONObject.parseObject(JSONObject.toJSONString(result), List.class);

        //表头数组
        String[] lables = new String[]{"文件名", "问题", "回答","路径"};
        //查询数据对应的属性数组
        String[] fields = new String[]{"fileName", "question", "answer","filePath"};
        String title = "test.xlsx";
        String headTitle = "指令集";
        //if (result.size() > 1) {
        //title = result.get(0).getName() + "(" + result.get(0).getCode() + ")" + "历史数据.xlsx";
        //headTitle = result.get(0).getName() + "(" + result.get(0).getCode() + ")" + "历史数据";
        //}
        ExcelExportUtil.export(outputFilePath, list, lables, fields, title);

    }

}